package com.titaniume.readwrite;


import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.readwrite
 * @ClassName: ReadWriteLockDemo
 * @Author: huangrenfei
 * @Description:  读写锁 ReentrantReadWriteLock 场景: 使用 ReentrantReadWriteLock 对一个 hashmap 进行读和写操作
 * @Date: 2021/11/24 13:39
 * @Version: 1.0
 */

//创建资源类
class MyCache {

    //创建一个map
    private volatile Map<String, Object> map = new HashMap<>();

    //创建读写锁对象
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    //放暑假
    public  void put(String key,String value) {

        //添加写锁
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写操作");
            //暂停一会
            TimeUnit.MICROSECONDS.sleep(300);

            //放入数据
            map.put(key,value);

            System.out.println(Thread.currentThread().getName() +"写完了-->" + key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放写锁
            rwLock.writeLock().unlock();
        }
    }

    //取数据
    public  Object get(String key){
        //添加读锁
        rwLock.readLock().lock();
        Object result = null;
        try {
            System.out.println(Thread.currentThread().getName() +"正在读操作" + key );
            //暂停一会
            TimeUnit.MICROSECONDS.sleep(300);
            result = map.get(key);
            System.out.println(Thread.currentThread().getName() +"取完了==>" + key );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放读锁
            rwLock.readLock().unlock();
        }
        return  result;
    }

}


public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();

        //创建线程放入数据
        for (int i = 1; i <= 5; i++) {
            final  int num = i;
            new Thread( () ->{
                myCache.put(num + "",num+"");
            },String.valueOf(i)).start();
        }

        //创建线程取出数据
        for (int i = 1; i <= 5; i++) {
            final  int num = i;
            new Thread( () ->{
                myCache.get(num +"");
            },String.valueOf(i)).start();
        }
    }
}
